import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { message } from "antd";
import { drugInvtAlertApi } from "@/api/erp/drug/inventoryWarning";
import { useTranslation } from "react-i18next";
import "./index.less";
import { drugs } from "@/api/MedicalExamination";
let reload: Function;
let pkId: string;
const index = (props: { register: Fn }) => {
	const { t } = useTranslation();
	const en_vi = "drugStorage.drugManagement.inventoryWarning";
	const formSchema: FormSchema[] = [
		{
			label: t(`${en_vi}.drug`),
			field: "drugId",
			component: "ApiSelect",
			componentProps: {
				api: drugs,
				labelField: "drugName",
				valueField: "drugId"
			}
		},
		{
			label: t(`${en_vi}.mediumAlertValue`),
			field: "moderate",
			component: "InputNumber"
		},
		{
			label: t(`${en_vi}.highAlertValue`),
			field: "height",
			component: "InputNumber"
		},
		{
			label: t(`${en_vi}.remindWhenOutOfStock`),
			field: "isNull",
			component: "RadioGroup",
			componentProps: {
				options: [
					{
						label: t("erp.warehouseGroupType.open"),
						value: "0"
					},
					{
						label: t("erp.warehouseGroupType.close"),
						value: "1"
					}
				]
			}
		},
		{
			label: t(`erp.warehouses.status`),
			field: "status",
			component: "RadioGroup",
			componentProps: {
				options: [
					{
						label: t("erp.warehouseGroupType.open"),
						value: "0"
					},
					{
						label: t("erp.warehouseGroupType.close"),
						value: "1"
					}
				]
			}
		}
	];

	const [registerDrawer, { closeDrawer }] = useDrawerInner(props.register, async data => {
		reload = data.reload;
		await resetFields();
		if (data.record) {
			console.log(data.record);
			pkId = data.record.pkId;
			setFieldsValue(data.record);
		}
	});

	const [register, { validateFields, setFieldsValue, resetFields }] = useForm({
		schemas: formSchema,
		labelWidth: 100,
		baseColProps: {
			span: 24
		},
		initialValues: {
			status: "0",
			isNull: "0"
		}
	});
	const handleSubmit = async () => {
		const formValue = await validateFields();
		let api = drugInvtAlertApi.drugInvtAlertCreate;
		if (pkId) {
			api = drugInvtAlertApi.drugInvtAlertUpdate;
		}
		const res = await api({ ...formValue, pkId });
		if (res) {
			pkId ? message.success(t("kevin_ui.updateSuccess")) : message.success(t("kevin_ui.addedSuccessfully"));
			reload();
			closeDrawer();
		}
	};
	return (
		<BasicDrawer showFooter={true} {...props} register={registerDrawer} ok={handleSubmit}>
			<div className="warehouses">
				<BasicForm register={register}></BasicForm>
			</div>
		</BasicDrawer>
	);
};
export default index;
